

layui.use('table', function () {
    var table = layui.table;
    //第一个实例
    table.render({
        elem: '#demo'       //id选择器
        , url: '/gra/findAllGrade' //数据接口
        , method: 'post'
        , page: true //开启分页
        , toolbar: 'default' //开启头部工具栏，此处显示默认图标，可以自定义模板，详见文档
        , limit: 7          //默认是10
        , id:'testReload'
        , limits: [3, 5, 7]
        , cols: [[
            { width: 80, type: 'checkbox' },
            { field: 'pkId', width: 100, title: '主键ID', sort: true,hide:true },
            { field: 'gradeId', width: 90,title: '班级id', sort: true,},
            { field: 'gradeName', width: 120,title: '班级名称' },
            { field: 'classTeacherId', width: 100,title: '班主任id' },
            { field: 'classTeacherName', width: 120,title: '班主任姓名' , },
            { field: 'lecturerId', width: 90,title: '讲师id', sort: true },
            { field: 'lecturerName', width: 120,title: '讲师姓名' },
            { field: 'studentsNumber', width: 120,title: '学生数量', sort: true },
            { field: 'classroomClassroomId', width: 140,title: '所在教室id', sort: true },
            { field: 'classroomClassroomNumber', width: 140,title: '所在教室编号', hide:true },

            { field: 'createTime', width: 170,title: '创建时间', sort: true },
            { field: 'updateTime', width: 170,title: '修改时间', sort: true },
            { field: 'remark', width: 200, title: '操作', toolbar: '#barDemo' },
        ]],


        done: function(res, curr, count) {          //对表格数据的处理

            // $("[data-field='useStatus']").children().each(function () {
            //     if ($(this).text() == '1') {
            //         $(this).text('未使用');
            //     } else if ($(this).text() == '0') {
            //         $(this).text('使用中');
            //     }
            // });

        },
        parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": res.data //解析数据列表
            };
        },
        request: {
            pageName: 'page' // 页码的参数名称，默认：page
            , limitName: 'limit' //每页数据量的参数名，默认：limit
        },
    });
    //监听排序
    //升序降序后重新渲染
    table.on('sort(test)',function(obj){
        table.reload('testReload', {
            initSort:obj
        });
    });
    table.reload('testReload',{})


    //表单数据重载
    var $ = layui.$,active = {
        reload: function(){
            var gradeName=$("#gradeName");
            var classTeacherName=$("#classTeacherName");
            var lecturerName=$("#lecturerName");
            var studentsNumber=$("#studentsNumber");

            //执行重载
            table.reload('testReload', {
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                ,where: {
                    gradeName: gradeName.val(),
                    classTeacherName: classTeacherName.val(),
                    lecturerName: lecturerName.val(),
                    studentsNumber:studentsNumber.val()
                }
            });
        }
    };
    $('.demoTable .layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });



    //监听头工具事件----添加
    table.on('toolbar(test)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id)
            ,data = checkStatus.data; //获取选中的数据
        switch(obj.event){
            case 'add':
                // layer.msg('添加')
                layer.open({
                    type: 1 //此处以iframe举例
                    , title:'班级信息录入表'
                    , area: ['800px', '650px']
                    , shade: 0
                    , maxmin: true
                    ,content:$("#insertPage")
                })

                $("#insertGra").click(function () {
                    var istData={
                        "gradeId":$("#addGradeId").val(),
                        "gradeName":$("#addGradeName").val(),
                        "classTeacherId":$("#addClassTeacherId").val(),
                        "classTeacherName":$("#addClassTeacherName").val(),
                        "lecturerId":$("#addLecturerId").val(),
                        "lecturerName":$("#addLecturerName").val(),
                        "studentsNumber":$("#addStudentsNumber").val(),
                        "classroomClassroomId":$("#addClassroomClassroomId").val(),
                        "classroomClassroomNumber":$("#addClassroomClassroomNumber").val()
                    }

                    $.ajax({
                        type:"post",
                        url:'/gra/addGrade',
                        data:JSON.stringify(istData),                                            //JS对象转换为字符串
                        contentType: "application/json;charset=utf-8",
                        dataType:"json",
                        success:function (istData) {
                            if(istData=='1'){
                                layer.msg('添加成功',{icon:6,time:1000},function () {
                                    window.location.reload();
                                })
                            }else if(istData=='0'){
                                layer.msg('添加失败',{icon:5,time:1000},function () {
                                    window.location.reload();
                                })
                            }
                        },error:function (error) {
                            layer.msg("添加请求失败")
                        }

                    });
                })
                break;
            case 'update':
                if(data.length === 0){
                    layer.msg('请选择一行');
                } else if(data.length > 1){
                    layer.msg('只能同时编辑一个');
                } else {
                    layer.alert('编辑 [id]：'+ checkStatus.data[0].id);
                }
                break;
            case 'delete':
                if(data.length === 0){
                    layer.msg('请选择一行');
                } else {
                    layer.msg('删除');
                    $.ajax({                //批量删除
                        type:"post",
                        url:basePathRoom+"/xxx",
                        contentType: "application/json;charset=utf-8",
                        data:JSON.stringify(json),
                        dataType:"json",
                        success:function (delData) {
                            if(delData > 1){
                                layer.msg('删除成功',{icon:6,time:1000},function () {
                                    window.location.reload();
                                })
                            }else if(delData < 1) {
                                layer.msg('删除失败', {icon: 5, time: 1000}, function () {
                                    window.location.reload();
                                })
                            }
                        },error:function (error) {
                            layer.msg("删除请求失败");
                        }
                    })
                }
                break;
        };
    });

    //监听行工具事件
    table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event //获得 lay-event 对应的值
            ,dropdown=layui.dropdown;
        if(layEvent === 'detail') {
            layer.msg('查看操作');
            //
            layer.open({
                type: 1 //此处以iframe举例
                , title:'班级========'+data.gradeName+'的信息'
                , area: ['800px', '600px']
                , shade: [0.1, '#393D49']
                , maxmin: true
                ,content:$("#selPage")
                ,success:function (){
                    //回显班级信息
                    $("#selGradeId").val(data.gradeId);
                    $("#selGradeName").val(data.gradeName);
                    $("#selClassTeacherId").val(data.classTeacherId);
                    $("#selClassTeacherName").val(data.classTeacherName);
                    $("#selLecturerId").val(data.lecturerId);
                    $("#selLecturerName").val(data.lecturerName);
                    $("#selStudentsNumber").val(data.studentsNumber);
                    $("#selClassroomClassroomId").val(data.classroomClassroomId);
                    $("#selClassroomClassroomNumber").val(data.classroomClassroomNumber);

                    //添加学生至当前班级
                    $("#addStu").click(function (){
                        let pkId = data.pkId
                        layer.open({
                            type:2
                            ,title:"班级学生添加界面"
                            ,area:['1500px','900px']
                            ,shade:0
                            ,minmax:true
                            ,content:"/gra/findGra/"+pkId
                        })
                    })

                    //查询所在班级的学生
                    $("#selStu").click(function (){
                        let gradeId = data.gradeId
                        layer.open({
                            type:2
                            ,title:"班级学生查看界面"
                            ,area:['1000px','800px']
                            ,shade:0
                            ,minmax:true
                            ,content:"/gra/selGraStu/"+gradeId
                        })
                    })

                }

            })





        //
        } else if(layEvent === 'more'){
            //下拉菜单
            dropdown.render({
                elem: this //触发事件的 DOM 对象
                ,show: true //外部事件触发即显示
                ,data: [{
                    title: '编辑'
                    ,id: 'edit'
                },{
                    title: '删除'
                    ,id: 'del'
                }]
                ,click: function(menudata){
                    if(menudata.id === 'del'){
                        layer.confirm('真的删除行么', function(index){
                            obj.del(); //删除对应行（tr）的DOM结构
                            //layer.close(index);
                            //向服务端发送删除指令

                            $.ajax({
                                type:'post',
                                url:'/gra/delGrade',
                                data:JSON.stringify(data),
                                contentType:'application/json;charset=utf-8',
                                dataType:"json",
                                success:function (data) {
                                    if(data=='1'){
                                        layer.msg('删除成功',{icon:6,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }else if(data=='0'){
                                        layer.msg('删除失败',{icon:5,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }
                                },error:function (error) {
                                    alert("请求失败");
                                }

                            })
                        })
                        ;
                    } else if(menudata.id === 'edit'){

                        layer.msg('编辑操作,当前行 ID:'+ data.stuId);
                        layer.open({
                            type: 1 //此处以iframe举例
                            , title:'班级========'+data.gradeName+'的信息'
                            , area: ['800px', '600px']
                            , shade: 0
                            , maxmin: true
                            ,content:$("#updatePage")
                        })


                        //数据回显
                        $("#updGradeId").val(data.gradeId);
                        $("#updGradeName").val(data.gradeName);
                        $("#updClassTeacherId").val(data.classTeacherId);
                        $("#updClassTeacherName").val(data.classTeacherName);
                        $("#updLecturerId").val(data.lecturerId);
                        $("#updLecturerName").val(data.lecturerName);
                        $("#updStudentsNumber").val(data.studentsNumber);
                        $("#updClassroomClassroomId").val(data.classroomClassroomId);
                        $("#updClassroomClassroomNumber").val(data.classroomClassroomNumber);


                        //修改信息
                        $("#updateGra").click(function (){
                            var updData={
                                "pkId":data.pkId,
                                "gradeId":$("#updGradeId").val(),
                                "gradeName":$("#updGradeName").val(),
                                "classTeacherId":$("#updClassTeacherId").val(),
                                "classTeacherName":$("#updClassTeacherName").val(),
                                "lecturerId":$("#updLecturerId").val(),
                                "lecturerName":$("#updLecturerName").val(),
                                "studentsNumber":$("#updStudentsNumber").val(),
                                "classroomClassroomId":$("#updClassroomClassroomId").val(),
                                "classroomClassroomNumber":$("#updClassroomClassroomNumber").val(),
                            }
                            $.ajax({
                                type:"post",
                                url:'/gra/updGrade',
                                data:JSON.stringify(updData),
                                contentType: "application/json;charset=utf-8",
                                dataType:"json",
                                success:function (upddata) {
                                    if(upddata=='1'){
                                        layer.msg("修改成功",{icon:6,time:1000},function (){
                                            window.location.reload();
                                        })
                                    }else if (upddata=='0'){
                                        layer.msg('修改失败',{icon:5,time:1000},function (){
                                            window.location.reload();
                                        })
                                    }
                                },error:function (error){
                                    layer.msg("修改请求失败")
                                }
                            })
                        })



                    }
                }
                ,align: 'right' //右对齐弹出（v2.6.8 新增）
                ,style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
            })
        }
    });
});

//JS
layui.use(['element', 'layer', 'util'], function(){
    var element = layui.element
        ,layer = layui.layer
        ,util = layui.util
        ,$ = layui.$;

    //头部事件
    util.event('lay-header-event', {
        //左侧菜单事件
        menuLeft: function(othis){
            layer.msg('展开左侧菜单的操作', {icon: 0});
        }
        ,menuRight: function(){
            layer.open({
                type: 1
                ,content: '<div style="padding: 15px;">处理右侧面板的操作</div>'
                ,area: ['260px', '100%']
                ,offset: 'rt' //右上角
                ,anim: 5
                ,shadeClose: true
            });
        }
    });

});

layui.config({
    version: '1623988781494' //为了更新 js 缓存，可忽略
});
layui.use('form', function(){
    var form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功

    //……

    //如果你的 HTML 是动态生成的，自动渲染就会失效
    //因此你需要在相应的地方，执行下述方法来进行渲染
    form.render('select');
});